package com.keliangliu.demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.ImmediateEventExecutor;
import org.apache.catalina.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

public class NettyServer {


    public static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static void main(String[] args) {
        NettyServer server = new NettyServer();
        server.serverStart();
    }

    public void serverStart() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 负责连接 用来accept
        EventLoopGroup workerGroup = new NioEventLoopGroup(2); // 负责处理

        ServerBootstrap sb = new ServerBootstrap(); // 辅助启动类
        try {
            ChannelFuture f = sb.group(bossGroup,workerGroup) // 指定线程池组
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new ServerChildHandler());
                        }
                    })
                    .bind(9999)
                    .sync();
            f.channel().closeFuture().sync(); // close->ChannelFuture
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

class  ServerChildHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        NettyServer.clients.add(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        // 删除出现异常的客户端channel，并关闭连接
        NettyServer.clients.remove(ctx.channel());
        ctx.close();
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channelRead");
        ByteBuf buf = (ByteBuf)msg;
//        ctx.writeAndFlush(buf);
        System.out.println(buf);
        NettyServer.clients.writeAndFlush(buf); // 将Server端接收到的信息广播到client端
    }

}
